package com.example.lightcontrol.message;

import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;

import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.example.lightcontrol.CommonConfig;

/*
 * this class is used to as mapper of socket channel
 */
public class SyncMessageHandler {
	private Socket socket;
	private Handler myHandler = new MyHandler();
	public static SyncMessageHandler instance = new SyncMessageHandler();
	
	private SyncMessageHandler() {
		
	}
	
	public String invoke( Message msg ) {
		this.myHandler.sendMessage( msg );
		//TODO
		return "";
	}
	
	public void init( Socket socket ) {
		this.socket = socket;
	}
	
	class MyHandler extends Handler {
		public MyHandler() {
		}

		@Override
		public void handleMessage(Message msg) {
			switch( msg.what ) {
			case CommonConfig.MESSAGE_TYPE_LIGH_CONTROL:
				if ( msg.arg1 == 1 ) {
					sendMessageOut( "open" );
				} else if ( msg.arg1 == 0 ) {
					sendMessageOut( "close" );
				}
				break;
			case CommonConfig.MESSAGE_TYPE_LIGH_STATE:
				sendMessageOut( "getState" );
				break;
			default:
				break;
			}
		}
	}
	
	private void sendMessageOut( String command ) {
		if ( socket != null && socket.isConnected() ) {
			try {
				PrintWriter out = new PrintWriter(new BufferedWriter(
						new OutputStreamWriter(socket.getOutputStream())), true);
				out.println( command );
				out.flush();

			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	
	protected void receive() {
		new Thread() {
			public void run() {
				
				if ( socket != null && socket.isConnected() ) {
					try {
						DataInputStream input = (DataInputStream) socket.getInputStream();
						
						String got = input.readUTF();
						String[] separated = got.split( "," );
						String type = separated[0];
						String value = separated[1];
						if ( type.equals( "state" )) {
							//setOnOffState( value );
						}
						
					} catch (Exception e) {
						Log.e("Received", "exception", e);
					}
				}

				try {
					sleep(100);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				
			}
		}.start();
	}
}
